package com.epalmpay.service.iccard.impl;

import java.util.*;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import com.epalmpay.bean.OtherCouponBean;
import com.epalmpay.bean.OtherIcCardBean;
import com.epalmpay.dto.iccard.IcCardImportInDTO;
import com.epalmpay.dto.iccard.IcCardInDTO;
import com.epalmpay.dto.iccard.IcCardOutDTO;
import com.epalmpay.dto.iccard.IcCardShowListDTO;
import com.epalmpay.entity.Coupon;
import com.epalmpay.entity.CouponUser;
import com.epalmpay.entity.Group;
import com.epalmpay.entity.Member;
import com.epalmpay.entity.MemberICCardInfo;
import com.epalmpay.entity.Page;
import com.epalmpay.entity.Response;
import com.epalmpay.entity.TradeOffline;
import com.epalmpay.enumdef.ActivityEnum;
import com.epalmpay.enumdef.BizEnum.PaymentScene;
import com.epalmpay.enumdef.BizEnum.PaymentType;
import com.epalmpay.enumdef.BizEnum.TransactionStatus;
import com.epalmpay.enumdef.BizEnum.TransactionType;
import com.epalmpay.exception.ApplicationException;
import com.epalmpay.mapper.MemberICCardInfoMapper;
import com.epalmpay.mapper.MemberMapper;
import com.epalmpay.mapper.TradeOfflineMapper;
import com.epalmpay.service.group.IGroupService;
import com.epalmpay.service.iccard.IIcCardService;
import com.epalmpay.service.weixin.IWalletService;
import com.epalmpay.util.SysUtils;
import com.epalmpay.util.Tools;
import com.epalmpay.util.payplat.DateUtils;
import com.epalmpay.util.payplat.UtilFun;

import sun.util.logging.resources.logging;

@Service("icCardService")
public class IcCardServiceImpl implements IIcCardService{

	@Resource
	private MemberICCardInfoMapper memberIcCardInfoMapper;
	
	@Resource
	private TradeOfflineMapper tradeOfflineMapper;//线下交易表
	
	@Resource
	private MemberMapper memberMapper;//会员信息
	
	@Resource
	private IGroupService groupService;
	
	@Resource
	private IWalletService walletService;
	
	/**
	 * 实体卡列表分页
	 */
	@Override
	public IcCardShowListDTO selectIcCardList(IcCardInDTO icCardInDTO, Page page) {
		// TODO Auto-generated method stub
		
		IcCardShowListDTO icCardShowListDTO = new IcCardShowListDTO();
		Map<String,Object> param = new HashMap<String,Object>();
		
		param.put("status",icCardInDTO.getStatus());
		param.put("switchStatus",icCardInDTO.getSwitchStatus());
		param.put("gmtStart",icCardInDTO.getGmtStart());
		param.put("gmtEnd",icCardInDTO.getGmtEnd());
		param.put("noOrPhone", icCardInDTO.getNoOrPhone());
		param.put("groupId", icCardInDTO.getGroupId());
		
		int sumCount = memberIcCardInfoMapper.selectIcCardListCount(param);
		page.setTotalResult(sumCount);
		if(sumCount<=0){
			return icCardShowListDTO;
		}
		
		param.put("limit", page.getShowCount());
		param.put("start", page.getShowCount() * (page.getCurrentPage() - 1));
		
		List<IcCardOutDTO> icCardShowListDTOList = memberIcCardInfoMapper.selectIcCardByWhere(param);
		icCardShowListDTO.setIcCardOutDTOList(icCardShowListDTOList);
		return icCardShowListDTO;
	}
	
	
	@Override
	public List<IcCardOutDTO> selectIcCardStatusList(){
		List<IcCardOutDTO> icCardStatusList = memberIcCardInfoMapper.selectIcCardStatusList();
		return icCardStatusList;
	}

	@Override
	public boolean insertIcCardBatch(IcCardInDTO icCardInDTO) {
		// TODO Auto-generated method stub
		DefaultTransactionDefinition def = new DefaultTransactionDefinition();
		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); // 事物隔离级别，开启新事务
		
		MemberICCardInfo memberICCardInfo = new MemberICCardInfo();
		memberICCardInfo.setGroupId(icCardInDTO.getGroupId());
		memberICCardInfo.setInitValue(icCardInDTO.getInitValue());
		
		for(int i=0;i<icCardInDTO.getSum();i++){
			memberICCardInfo.setIccardNo(DateUtils.getDateTimeString("yyyy", new Date())+UtilFun.createRandomNum(8));//随机生成12位实体卡号
			memberICCardInfo.setIccardPwd(UtilFun.createRandomNum(6));//随机生成6位随机数实体卡密码
			memberIcCardInfoMapper.insertBatch(memberICCardInfo);
		}
		return true;
	}

	@Override
	public boolean updateSwitchStatus(IcCardInDTO icCardInDTO) {
		// TODO Auto-generated method stub
		int a=0;
		MemberICCardInfo memberICCardInfo = new MemberICCardInfo();
		if (icCardInDTO.getSwitchStatus()!=null) {
			memberICCardInfo.setSwitchStatus(icCardInDTO.getSwitchStatus());
		}
		if (icCardInDTO.getId()!=null) {
			memberICCardInfo.setId(icCardInDTO.getId());
		}
		
		try {
			memberIcCardInfoMapper.updateByPrimaryKeySelective(memberICCardInfo);
			return true; 
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false; 
		
	}
	
	@Override
	public boolean updateIcCardById(IcCardInDTO icCardInDTO) {
		// TODO Auto-generated method stub
		MemberICCardInfo memberICCardInfo = new MemberICCardInfo();
		if (icCardInDTO.getId()!=null) {
			memberICCardInfo.setId(icCardInDTO.getId());
		}
		if(Tools.notEmpty(icCardInDTO.getIccardPwd())){
			memberICCardInfo.setIccardPwd(icCardInDTO.getIccardPwd());
		}
		if(icCardInDTO.getInitValue()!=null){
			memberICCardInfo.setInitValue(icCardInDTO.getInitValue());
		}
		if(icCardInDTO.getStatus()!=null){
			memberICCardInfo.setStatus(icCardInDTO.getStatus());
		}
		if(icCardInDTO.getSwitchStatus()!=null){
			memberICCardInfo.setSwitchStatus(icCardInDTO.getSwitchStatus());
		}
		
		try {
			memberIcCardInfoMapper.updateByPrimaryKeySelective(memberICCardInfo);
			return true;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}
	
	@Override
	public IcCardOutDTO selectIcCardById(IcCardInDTO icCardInDTO) {
		// TODO Auto-generated method stub
		IcCardOutDTO icCardOutDTO = new IcCardOutDTO();
		if (icCardInDTO.getId()!=null) {
			Long id=icCardInDTO.getId();
			MemberICCardInfo  memberICCardInfo=memberIcCardInfoMapper.selectByPrimaryKey(id);
			if(memberICCardInfo.getMemberId()!=null){
				icCardOutDTO.setMemberId(memberICCardInfo.getMemberId());
			}
			if(memberICCardInfo.getId()!=null){
				icCardOutDTO.setId(memberICCardInfo.getId());
			}
			if(Tools.notEmpty(memberICCardInfo.getIccardNo())){
				icCardOutDTO.setIccardNo(memberICCardInfo.getIccardNo());
			}
			if(Tools.notEmpty(memberICCardInfo.getIccardPwd())){
				icCardOutDTO.setIccardPwd(memberICCardInfo.getIccardPwd());
			}
			if(Tools.notEmpty(Tools.date2Str(memberICCardInfo.getGmtCreate()))){
				icCardOutDTO.setGmtCreate(memberICCardInfo.getGmtCreate());
			}
			if(memberICCardInfo.getGroupId()!=null){
				icCardOutDTO.getGroupId();
			}
			if(Tools.notEmpty(Tools.date2Str(memberICCardInfo.getGmtPinless()))){
				icCardOutDTO.setGmtPinless(memberICCardInfo.getGmtPinless());
			}
			if(Tools.notEmpty(Tools.date2Str(memberICCardInfo.getGmtModified()))){
				icCardOutDTO.setGmtModified(memberICCardInfo.getGmtModified());
			}
			if(memberICCardInfo.getSwitchStatus()!=null){
				icCardOutDTO.setSwitchStatus(memberICCardInfo.getSwitchStatus());
			}
			if(memberICCardInfo.getInitValue()!=null){
				icCardOutDTO.setInitValue(memberICCardInfo.getInitValue());
			}
			if(memberICCardInfo.getStatus()!=null){
				icCardOutDTO.setStatus(memberICCardInfo.getStatus());
			}
		}
		return icCardOutDTO;
	}


	@Override
	public boolean deleteIcCardById(IcCardInDTO icCardInDTO) {
		// TODO Auto-generated method stub

		MemberICCardInfo memberICCardInfo = new MemberICCardInfo();
		if(icCardInDTO.getId()!=null){
			Long id=icCardInDTO.getId();
			memberICCardInfo=memberIcCardInfoMapper.selectByPrimaryKey(id);
			if(memberICCardInfo.getMemberId()==null){
				if(memberICCardInfo.getStatus()==1){
					int result=memberIcCardInfoMapper.deleteByPrimaryKey(id);
					return true;
				}else{
					//已被使用
					return false;
				}
			}else{
				//有用户
				return false;
			}
		}
		//没有实体卡ID
		return false;
	}


	@Override
	public IcCardOutDTO selectIcCardByIcCardNo(IcCardInDTO icCardInDTO) throws ApplicationException {
		// TODO Auto-generated method stub
		IcCardOutDTO icCardOutDTO=new IcCardOutDTO();
		if(icCardInDTO.getIccardNo()!=null&&icCardInDTO.getIccardNo()!=""){
			String iccardNo=icCardInDTO.getIccardNo();
			MemberICCardInfo memberICCardInfo=memberIcCardInfoMapper.getByICCardNo(iccardNo);
			
			icCardOutDTO.setIccardPwd(memberICCardInfo.getIccardPwd());//获取初始密码
			icCardOutDTO.setStatus(memberICCardInfo.getStatus());//获取卡状态
			icCardOutDTO.setSwitchStatus(memberICCardInfo.getSwitchStatus());//获取卡启用禁用状态
			icCardOutDTO.setMemberId(memberICCardInfo.getMemberId());//获取会员ID，可能为空
			icCardOutDTO.setGroupId(memberICCardInfo.getGroupId());//获取渠道ID
		}
		return icCardOutDTO;
	}

	@Override
	public Response updatePinlessIcCard(String icCardNo, String memberId){
		try {
			MemberICCardInfo memberIcCardInfo=memberIcCardInfoMapper.getByICCardNo(icCardNo);
			TradeOffline tradeOffline = new TradeOffline();//线下交易记录表实体
			if(memberIcCardInfo==null||memberIcCardInfo.getStatus()!=1){
				return Response.getError("实体卡已绑定或不可用");
			}
			memberIcCardInfo.setMemberId(Long.parseLong(memberId));
			memberIcCardInfo.setStatus(2);
			memberIcCardInfo.setSwitchStatus(1);
			memberIcCardInfo.setGmtPinless(new Date());
			memberIcCardInfoMapper.updateByPrimaryKeySelective(memberIcCardInfo);
			String addValue=memberIcCardInfo.getInitValue()*100+"";
			
			
			Member resultMember=memberMapper.selectByPrimaryKey(Long.parseLong(memberId));//根据会员ID，查找会员信息
			Group group=groupService.selectGroupInfo(memberIcCardInfo.getGroupId());//根据渠道ID，查找渠道详情
			
			String orderId="STK"+DateUtils.getDateTimeString("yyyyMMddHHmmss", new Date())+UtilFun.createRandomNum(6);
			
			//充值成功后，生成充值交易记录
			tradeOffline.setOrderId(orderId);//订单交易号由STK+年月日时分秒+11位随机数组成
			tradeOffline.setGroupId(memberIcCardInfo.getGroupId());
			tradeOffline.setGmtCreate(new Date());
			tradeOffline.setPayerId(Long.parseLong(memberId));//付款者ID
			tradeOffline.setPayerName(resultMember.getName());//付款者姓名
			tradeOffline.setPayerType((byte)7);//付款者类型,7代表会员
			tradeOffline.setReceiverId(memberIcCardInfo.getGroupId().toString());//收款者ID，认为是渠道ID
			tradeOffline.setReceiverName(group.getMerchantName());//收款者姓名,认为是渠道名
			//tradeOffline.setReceiverType(receiverType);//收款者类型，
			tradeOffline.setTransactionType((byte)TransactionType.Recharge.getType());//交易类型,充值
			tradeOffline.setSubType((byte)PaymentScene.AppOut.getType());//交易子类型,app外部支付
			tradeOffline.setOrderAmount(Integer.parseInt(addValue));//订单金额
			tradeOffline.setRealAmount(Integer.parseInt(addValue));//实付金额
			tradeOffline.setPayType((byte)13);//设置支付方式为13，钱包支付
			tradeOffline.setIsWallet(true);//是否钱包交易,是
			tradeOffline.setTransactionStatus((byte)TransactionStatus.Success.getType());
			
			walletService.updateLockedAmount(memberId,"1",addValue,"0",0,orderId);
			
			//tradeOffline.setMerchantNo(merchantNo);//商户编号
			//tradeOffline.setTransNo(transNo);//交易流水号
			//tradeOffline.setTransOrderNo(transOrderNo);//交易机构订单号 
			//tradeOffline.setCheckStatus(checkStatus);//账对状态
			int resultInsertTradeOffline=tradeOfflineMapper.insertSelective(tradeOffline);
			if(resultInsertTradeOffline<=0){
				return Response.getError("交易记录生成失败,绑卡失败");
			}
			return Response.getSuccess("绑定成功");
		} catch (ApplicationException ae) {
			ae.setErrMsg("绑卡失败");
			return Response.getError("绑卡失败");
		}
	}


	@Override
	public IcCardOutDTO selectIcCardByMemberIdAndStatus(Long memberId,Long groupId) throws ApplicationException {
		// TODO Auto-generated method stub
		IcCardOutDTO icCardOutDTO=new IcCardOutDTO();
		MemberICCardInfo memberICCardInfo=new MemberICCardInfo();
		memberICCardInfo.setMemberId(memberId);
		memberICCardInfo.setGroupId(groupId);
		MemberICCardInfo resultMemberICCardInfo;
		try {
			resultMemberICCardInfo = memberIcCardInfoMapper.selectIcCardByMemberIdAndStatus(memberICCardInfo);
			if(resultMemberICCardInfo!=null){
				icCardOutDTO.setId(resultMemberICCardInfo.getId());
				icCardOutDTO.setIccardNo(resultMemberICCardInfo.getIccardNo());
				icCardOutDTO.setStatus(resultMemberICCardInfo.getStatus());
				icCardOutDTO.setSwitchStatus(resultMemberICCardInfo.getSwitchStatus());
				if(icCardOutDTO.getStatus().equals(2)){
					icCardOutDTO.setErrorCode("-2","该会员在本渠道有已绑定的实体卡");
				}else if(icCardOutDTO.getStatus().equals(4)){
					icCardOutDTO.setErrorCode("-3","该会员在本渠道有已挂失但未废弃的实体卡");
				}else if (icCardOutDTO.getStatus().equals(3)){
					icCardOutDTO.setErrorCode("-4","该会员在本渠道有已废弃的实体卡");
				}
			}else{
				icCardOutDTO.setErrorCode("1","该会员在本渠道下没有正在使用中的实体卡");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			icCardOutDTO.setErrorCode("-1","查询会员在本渠道的实体卡使用情况时出错");
		}
		return icCardOutDTO;
	}


	@Override
	public IcCardOutDTO insertIcCardImport(IcCardImportInDTO icCardImportInDTO) {
		// TODO Auto-generated method stub
		IcCardOutDTO icCardOutDTO = new IcCardOutDTO();
		MemberICCardInfo memberICCardInfo=new MemberICCardInfo();
		int allCount=0,successCount=0,errorCount=0;
		if(icCardImportInDTO!=null){
			List<OtherIcCardBean> icCardInfos =icCardImportInDTO.getIcCardInfos();
			if(icCardInfos.size()>0){
				for(OtherIcCardBean bean:icCardInfos){
					allCount++;
					MemberICCardInfo resultIcCardInfo=memberIcCardInfoMapper.selectIcCardByIcCardNo(bean.getIccardNo());
					if(resultIcCardInfo!=null&&resultIcCardInfo.getIccardNo().equals(bean.getIccardNo())){
						errorCount++;//卡号冲突，添加失败
						icCardOutDTO.setErrorCode("-2","+"+bean.getIccardNo()+"+卡号冲突");
					}else{
						//本行实体卡号和数据库中的卡号不冲突，可以添加
						memberICCardInfo.setIccardNo(bean.getIccardNo());
						memberICCardInfo.setIccardPwd(bean.getIccardPwd());
						memberICCardInfo.setInitValue(bean.getInitValue());
						memberICCardInfo.setGroupId(icCardImportInDTO.getGroupId());
						if(memberIcCardInfoMapper.insertBatch(memberICCardInfo)>0){
							successCount++;//添加成功
						}
					}
				}
			}
		}else{
			icCardOutDTO.setErrorCode("-1","导入输入不可为空");
		}
		icCardOutDTO.setAllCount(allCount);
		icCardOutDTO.setSuccessCount(successCount);
		icCardOutDTO.setErrorCount(errorCount);
		return icCardOutDTO;
		
	}


	@Override
	public int updateAutoDiscardIcCard(IcCardInDTO icCardInDTO) {
		// TODO Auto-generated method stub
		MemberICCardInfo memberICCardInfo =new MemberICCardInfo();
		memberICCardInfo.setGroupId(icCardInDTO.getGroupId());
		int result=0;
		List<MemberICCardInfo> timeOut=memberIcCardInfoMapper.selectTimeOut(memberICCardInfo);
		memberICCardInfo.setStatus(3);
		memberICCardInfo.setSwitchStatus(0);
		if(timeOut!=null){
			//循环去废弃符合条件的实体卡
			for(MemberICCardInfo in:timeOut){
				memberICCardInfo.setId(in.getId());
				result=memberIcCardInfoMapper.updateByPrimaryKeySelective(memberICCardInfo);
			}
		}
		return result;
	}

}
